/**
 * 操作相关
 */
var OPT = {
    /**
     * 注册
     */
    register: () => {
        layer.open({
            id: 'registerLayer',
            type: 1,
            title: ['注册'],
            skin: 'layui-layer-molv',
            area: '400px',
            offset: 'auto',
            content: $('#registerDialog'),
            btn: ['提交', '取消'],
            // 弹窗加载完成后回调
            success: (layero) => {
                layero.find('.layui-layer-btn').css('text-align', 'center');
                form.render();
            },
            yes: (layero, index) => {
                SOCKET.start();
            },
            cancel: (index, layero) => {
                layer.close(index)
            }
        })
    },
    /**
     * 呼叫
     */
    call: () => {
        if (SOCKET.ws === null) {
            layer.msg('您还没有注册，请先注册哦！', {icon: 5, time: 1500});
            return false;
        }
        layer.open({
            id: 'callLayer',
            type: 1,
            title: ['注册'],
            skin: 'layui-layer-molv',
            area: '300px',
            offset: 'auto',
            content: $('#callDialog'),
            btn: ['提交', '取消'],
            // 弹窗加载完成后回调
            success: (layero) => {
                layero.find('.layui-layer-btn').css('text-align', 'center');
            },
            yes: (layero, index) => {
                RTC.call();
            },
            cancel: (index, layero) => {
                layer.close(index)
            }
        })
    },
    /**
     * 摄像头
     */
    videoSwitch: () => {
        if (roomList.length === 0) {
            layer.msg('请先开启直播！', {icon: 5, time: 1500});
            return false;
        }
        let flag = OPT.getVideoStatus('localVideo')
        if (flag === null) return false;
        
        roomList.forEach(async (user) => {
            if (user.userId !== userId) {
                let pcKey = userId + '-' + user.userId;
                let pc = RtcPcMaps.get(pcKey);
                if (pc) {
                    const senders = pc.getSenders();
                    const send = senders.find((s) => s.track.kind === 'video');
                    if (send) {
                        if (flag) {
                            send.track.enabled = false;
                        } else {
                            send.track.enabled = true;
                        }
                    }
                }
            }
        });
        if (flag) {
            layer.msg('您已关闭视频！', {icon: 1, time: 1500});
        } else {
            layer.msg('您已打开视频！', {icon: 1, time: 1500});
        }
    },
    /**
     * 麦克风
     */
    audioSwitch: () => {
        if (roomList.length === 0) {
            layer.msg('请先开启直播！', {icon: 5, time: 1500});
            return false;
        }
        let flag = OPT.getAudioStatus('localVideo')
        if (flag === null) return false;

        roomList.forEach(async (user) => {
            if (user.userId !== userId) {
                let pcKey = userId + '-' + user.userId;
                let pc = RtcPcMaps.get(pcKey);
                if (pc) {
                    const senders = pc.getSenders();
                    const send = senders.find((s) => s.track.kind === 'audio');
                    if (send) {
                        if (flag) {
                            send.track.enabled = false;
                        } else {
                            send.track.enabled = true;
                        }
                    }
                }
            }
        });
        if (flag) {
            layer.msg('您已关闭麦克风！', {icon: 1, time: 1500});
        } else {
            layer.msg('您已打开麦克风！', {icon: 1, time: 1500});
        }
    },
    /**
     * 获取音频状态
     * @param domId
     * @returns {boolean|null}
     */
    getAudioStatus(domId) {
        let video = document.getElementById(domId)
        if (!video || !video.srcObject) return null;
        let stream = video.srcObject
        let tracks = stream.getAudioTracks();
        if (!tracks || tracks.length === 0) return null;
        return tracks[0].enabled;
    },
    /**
     * 获取视频状态
     * @param domId
     * @returns {boolean|null}
     */
    getVideoStatus(domId) {
        let video = document.getElementById(domId)
        if (!video || !video.srcObject) return null;
        let stream = video.srcObject
        let tracks = stream.getVideoTracks();
        if (!tracks || tracks.length === 0) return null;
        return tracks[0].enabled;
    },
    /**
     * 屏幕分享
     */
    shareScreen: () => {
        if (roomList.length === 0) {
            layer.msg('请先开启直播！', {icon: 5, time: 1500});
            return false;
        }
        const displayMediaStreamConstraints = {
            video: {
                cursor: "always"
            },
            audio: true
        };

        //获取分享窗口流
        if (navigator.mediaDevices.getDisplayMedia) {
            navigator.mediaDevices.getDisplayMedia(displayMediaStreamConstraints).then(mediaStream => {
                localStream = mediaStream;
                roomList.forEach(async (user) => {
                    if (user.userId !== userId) {
                        let pcKey = userId + '-' + user.userId;
                        let pc = RtcPcMaps.get(pcKey);
                        if (pc) {
                            const senders = pc.getSenders();
                            const send = senders.find((s) => s.track.kind === 'video');
                            send.replaceTrack(mediaStream.getVideoTracks()[0]);
                        }
                    }
                });

                //监听手动点击"停止分享"
                mediaStream.getVideoTracks()[0].onended = () => {
                    layer.msg('屏幕共享已关闭,正在切换为摄像头数据,请稍后...！', {icon: 1, time: 1500});
                    OPT.switchVideo();
                }
            }).catch(error => {
                console.log('获取屏幕分享流异常')
                layer.msg('您已取消屏幕分享', {icon: 2, time: 1500});
            });
        } else {
            console.log("navigator.mediaDevices.getDisplayMedia false");
            layer.msg('浏览器不支持屏幕共享', {icon: 2, time: 1500});
        }
    },
    /**
     * 切换为摄像头数据
     */
    async switchVideo() {
        localStream = await RTC.getLocalUserMedia();
        roomList.forEach(async (user) => {
            if (user.userId !== userId) {
                let pcKey = userId + '-' + user.userId;
                let pc = RtcPcMaps.get(pcKey);
                if (pc) {
                    const senders = pc.getSenders();
                    const send = senders.find((s) => s.track.kind === 'video');
                    send.replaceTrack(localStream.getVideoTracks()[0]);
                }
            }
        });
    },
    /**
     * 发送聊天消息
     */
    sendMessage: () => {
        if (!SOCKET.ws || SOCKET.ws.readyState !== WebSocket.OPEN) {
            layer.msg('连接已断开，请重新连接！', {icon: 5, time: 1500});
            return false;
        }

        const messageInput = document.getElementById('messageInput');
        const message = messageInput.value.trim();
        
        if (!message) {
            layer.msg('请输入消息内容！', {icon: 5, time: 1500});
            return false;
        }

        const timestamp = new Date().getTime();

        // 发送消息
        const params = {
            type: 'chat',
            targetUid: 'all',  // 'all' 表示广播给所有人
            userId: userId,
            message: message,
            timestamp: timestamp,
            roomId: roomId
        };

        try {
            SOCKET.sendMsg(params);
            console.log('Message sent:', params);

            // 显示自己发送的消息
            OPT.appendMessage({
                userId: userId,
                message: message,
                timestamp: timestamp,
                isSelf: true
            });

            // 清空输入框
            messageInput.value = '';
        } catch (error) {
            console.error('Error sending message:', error);
            layer.msg('消息发送失败，请重试！', {icon: 2, time: 1500});
        }
    },

    /**
     * 接收聊天消息
     */
    receiveMessage: (data) => {
        console.log('Received message data:', data);
        try {
            OPT.appendMessage({
                userId: data.userId,
                message: data.message,
                timestamp: data.timestamp,
                isSelf: false
            });
        } catch (error) {
            console.error('Error processing received message:', error);
        }
    },

    /**
     * 添加消息到聊天界面
     */
    appendMessage: (data) => {
        try {
            console.log('Appending message:', data);
            const chatMessages = document.getElementById('chatMessages');
            if (!chatMessages) {
                console.error('Chat messages container not found');
                return;
            }

            const messageDiv = document.createElement('div');
            messageDiv.className = `chat-message ${data.isSelf ? 'sent' : 'received'}`;

            const messageInfo = document.createElement('div');
            messageInfo.className = 'message-info';
            messageInfo.textContent = `${data.isSelf ? '我' : data.userId} - ${new Date(data.timestamp).toLocaleTimeString()}`;

            const messageContent = document.createElement('div');
            messageContent.className = 'message-content';
            messageContent.textContent = data.message;

            messageDiv.appendChild(messageInfo);
            messageDiv.appendChild(messageContent);
            chatMessages.appendChild(messageDiv);

            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        } catch (error) {
            console.error('Error appending message:', error);
        }
    }
}